import { useSize } from 'ahooks';
import { Flex, Input, message, Spin, TableProps, Tabs, TabsProps } from 'antd';
import dayjs from 'dayjs';
import React, { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';

import workbenchService from '@/api/services/workbenchService';
import { MessageDataType, KnowledgeReq } from '@/common/types';
import { SvgIcon } from '@/components/icon';
import NotData from '@/components/NotData';
import PagesHeader from '@/components/pages-header';
import Tables from '@/components/tables/tables';

import './index.scss';

import { useParams } from '@/router/hooks';
import useModal from '@/hooks/use-modal/useModal';
import TipDesc from '@/components/tipDesc/tipDesc';

const MessageCenter = () => {
  const modal = useModal('update', 'personnel', 'delete', 'edit');
  const [messageApi, contextHolder] = message.useMessage();
  const { appId = '', key = '0' } = useParams() as { appId: string; key: string };
  const [keys, setKeys] = React.useState(key);
  const [messageParam, setMessageParam] = React.useState<KnowledgeReq>({
    page: 1,
    pageSize: 10,
    searchText: '',
    status: key,
    startTime: dayjs().subtract(7, 'day').format('YYYY-MM-DD HH:mm:ss'),
    endTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  });
  // 返回值
  const [messageData, setMessageData] = React.useState({
    list: [],
    total: 0,
  });
  const [value, setValue] = React.useState('');
  const [scroll, setScroll] = useState({ x: 'calc(700px + 50%)', y: 'calc(80vh - 100px)' });
  const tableRef = useRef<HTMLDivElement>(null);
  const size = useSize(tableRef);
  const [count, setCount] = useState(0);
  // table选中的数据id
  const [tableSelectEdRows, setTableSelectEdRows] = useState<React.Key[]>([]);

  const router = useNavigate();

  /**
   * @description: 表格多选
   * @return {*}
   */
  const rowSelection: TableProps<MessageDataType>['rowSelection'] = {
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setTableSelectEdRows(newSelectedRowKeys);
    },
  };

  /**
   * @description: 获取未读消息
   */
  const getUnifiedMessageList = async () => {
    try {
      const res = await workbenchService.messageDetailApi(messageParam);
      setMessageData({
        list: res.notifications.map((item: any, index: number) => ({
          ...item,
          // 创建唯一 key，结合时间、用户名和索引
          key: `${index}`,
        })),
        total: res.total,
      });
      setCount(res.total);
      modal.personnel.close();
    } catch (error) {
      messageApi.error(error);
    } finally {
      modal.personnel.close();
    }
  };
  /**
   * @description: 获取已读消息
   */
  const getReadMessageList = async () => {
    try {
      const res = await workbenchService.messageDetailApi(messageParam);
      setMessageData({
        list: res.notifications.map((item: any, index: number) => ({
          ...item,
          // 创建唯一 key，结合时间、用户名和索引
          key: `${index}`,
        })),
        total: res.total,
      });
      modal.personnel.close();
    } catch (error) {
      messageApi.error(error);
    } finally {
      modal.personnel.close();
    }
  };

  // 监听表格大小变化，更新滚动条位置
  useEffect(() => {
    if (tableRef.current && size) {
      setScroll({
        x: 'calc(700px + 50%)',
        y: `${size?.height - 140}px`,
      });
    }
  }, [size]);

  useEffect(() => {
    if (keys === '0') {
      getUnifiedMessageList();
    } else {
      getReadMessageList();
    }
    modal.personnel.open();
  }, [messageParam]);

  /**
   * @description: 打开弹窗

  /**
   * @description: 切换Tabs
   * @param {string} key
   * @return {*}
   */
  const onChange = (key: string) => {
    setKeys(key);
    setMessageParam((prev) => ({
      ...prev,
      page: 1,
      pageSize: 10,
      searchText: '',
      status: key,
    }));
    setValue('');
    setTableSelectEdRows([]);
  };

  /**
   * @description: Tabs选项
   * @return {*}
   */
  const items: TabsProps['items'] = [
    {
      key: '0',
      label: (
        <div className="text-sm">
          未读消息
          {count > 0 && (
            <span
              // className="ml-2 inline-block h-5 rounded-full bg-@error-color px-1 text-center leading-5 text-white "
              className=" ml-2 inline-block h-5 rounded-full text-center leading-5 "
              // style={{ background: 'linear-gradient(180deg, #FF4646 0%, #FF8F62 100%)' }}
            >
              ({count > 99 ? '99+' : count})
            </span>
          )}
        </div>
      ),
    },
    {
      key: '1',
      label: <div className="text-sm">已读消息</div>,
    },
  ];

  /**
   * @description: TablesColumns
   * @return {*}
   */
  const columns: TableProps<MessageDataType>['columns'] = [
    {
      title: '消息主题',
      dataIndex: 'message',
      key: 'message',
      width: '30%',
      render: (_, record) => <div>{record?.message}</div>,
    },
    {
      title: '消息详情',
      dataIndex: 'detail',
      key: 'detail',
      width: '40%',
      render: (_, record) => <div>{record?.detail}</div>,
    },
    {
      title: '提交时间',
      dataIndex: 'action_time',
      key: 'action_time',
      width: '15%',
      render: (_, record) => {
        if (record?.action_time) {
          return <div>{dayjs(record.action_time).format('YYYY-MM-DD HH:mm')}</div>;
        }
        return <div>-</div>;
      },
    },
    {
      title: '操作',
      dataIndex: 'callTool',
      key: 'callTool',
      width: '10%',
      render: (_, record) => {
        return (
          <div className="flex cursor-pointer items-center font-bold text-@brand-color">
            <div
              className="mr-4 flex min-w-[60px] items-center"
              onClick={() => handleDetail(record)}
            >
              <SvgIcon icon="message-ic11" size="20" className="mr-1" />
              详情
            </div>
            {keys === '0' ? (
              <div
                className=" mr-2  flex min-w-[60px] items-center"
                onClick={() => handleIgnore(record)}
              >
                <SvgIcon icon="message-ic10" size="20" className="mr-1" />
                已读
              </div>
            ) : (
              <div
                className=" mr-2  flex min-w-[60px] items-center text-@error-color-hover"
                onClick={() => handleDelete(record)}
              >
                <SvgIcon icon="message-ic3" size="20" className="mr-1" />
                删除
              </div>
            )}
          </div>
        );
      },
    },
  ];

  /**
   * 查看详情
   * @param record
   */
  const handleDetail = async (record: MessageDataType) => {
    if (record?.next_actions?.forward_to === '') {
      messageApi.info('暂无详情');
      return;
    }
    if (record.next_actions.display_text === '立即处理') {
      messageApi.info('具体详情可前往应用中心通知查看');
      return;
    }
    const searchData = {
      notification_id: record.notification_id,
      status: 'IGNORED',
    };
    try {
      await workbenchService.updateMessageInformApi(searchData);
      setMessageParam((prev) => ({
        ...prev,
        page: 1,
        pageSize: 10,
        searchText: '',
        status: keys,
      }));
      router(record.next_actions.forward_to);
    } catch (error) {
      messageApi.error(error);
    }
  };
  /**
   * 忽略
   * @param record
   */
  const handleIgnore = async (record: MessageDataType) => {
    const searchData = {
      notification_id: record.notification_id,
      status: 'IGNORED',
    };
    try {
      await workbenchService.updateMessageInformApi(searchData);
      setMessageParam((prev) => ({
        ...prev,
        page: 1,
        pageSize: 10,
        searchText: '',
        status: keys,
      }));
      messageApi.success('已读成功');
    } catch (error) {
      messageApi.error(error);
    }
  };
  /**
   * 删除
   * @param record
   */
  const handleDelete = async (record: MessageDataType) => {
    const searchData = {
      notificationId: record.notification_id,
    };
    try {
      await workbenchService.deleteMessageInformApi(searchData);
      setMessageParam((prev) => ({
        ...prev,
        page: 1,
        pageSize: 10,
        searchText: '',
        status: keys,
      }));
      messageApi.success('删除成功');
    } catch (error) {
      messageApi.error(error);
    }
  };

  const changeMessage = async () => {
    if (tableSelectEdRows.length === 0) {
      messageApi.info('请选择');
      return;
    }
    try {
      if (keys === '0') {
        // TODO: 实现标记为已读逻辑
        await workbenchService.updateMessageInformApi({
          notification_id: tableSelectEdRows as string[],
          status: 'IGNORED',
        });
        messageApi.success('已读成功');
      } else {
        // TODO: 实现删除逻辑
        await workbenchService.deleteMessageInformApi({
          notificationId: tableSelectEdRows as string[],
        });
        messageApi.success('删除成功');
      }
    } catch (error) {
      messageApi.error('操作失败');
    }
    setTableSelectEdRows([]);
    setMessageParam((prev) => ({
      ...prev,
      page: 1,
      pageSize: 10,
      searchText: '',
      status: keys,
    }));
  };

  return (
    <div className="flex h-full flex-col">
      {contextHolder}
      <PagesHeader>
        消息中心
        <TipDesc title="集中管理用户收到的系统通知和消息" />
      </PagesHeader>
      <div className=" flex flex-1 flex-col rounded-default bg-[#FFF] px-5">
        <div className=" ">
          <Tabs defaultActiveKey={key} items={items} onChange={onChange} />
        </div>
        <div className=" mb-[16px] flex items-center justify-between ">
          <Input
            placeholder="请输入内容"
            onChange={(e: any) => {
              // 拿到搜索的数据
              setValue(e.target.value);
              setMessageParam((prev) => ({
                ...prev,
                page: 1,
                pageSize: 10,
                searchText: e.target.value,
                status: keys,
              }));
            }}
            value={value}
            suffix={<SvgIcon icon="work-ic6" size={16} />}
            className=" !rounded-md"
            style={{
              height: '32px',
              width: '240px',
            }}
          />
          <div className="flex h-4 items-center">
            {tableSelectEdRows.length > 0 && (
              <>
                <span className="text-[#1D2129]">
                  已选择 <span className="font-semibold">{tableSelectEdRows.length}</span> 项
                </span>
                <div
                  className={`${
                    keys === '0'
                      ? 'border-[#1B6DFA] text-@brand-color '
                      : 'border-@error-color-disabled bg-@error-color-light text-@error-color-hover'
                  } ml-4 flex h-8 cursor-pointer items-center rounded-md border px-2`}
                  onClick={changeMessage}
                >
                  <SvgIcon
                    icon={keys === '0' ? 'message-ic10' : 'message-ic3'}
                    className="mr-1"
                    size={20}
                  />
                  {keys === '0' ? '标记为已读' : '删除'}
                </div>
              </>
            )}
          </div>
        </div>
        {modal.personnel.isOpen ? (
          <Flex align="center" gap="middle" className="flex h-full items-center justify-center">
            <Spin size="large" />
          </Flex>
        ) : (
          <>
            {messageData.total > 0 ? (
              <div className="h-full flex-1 rounded-default  text-[#292D32]" ref={tableRef}>
                <Tables<MessageDataType>
                  rowSelection={{
                    type: 'checkbox',
                    ...rowSelection,
                    selectedRowKeys: tableSelectEdRows,
                  }}
                  rowKey="notification_id"
                  rowClassName="bg-[#F6F7FB]"
                  columns={columns}
                  dataSource={messageData.list}
                  pagination={false}
                  // scroll={scroll}
                  paginationProps={{
                    total: messageData.total,
                    current: messageParam.page,
                    pageSize: messageParam.pageSize,
                    onChange: (page, pageSize) => {
                      messageParam.page = page;
                      messageParam.pageSize = pageSize;
                      if (keys === '0') {
                        getUnifiedMessageList();
                      } else {
                        getReadMessageList();
                      }
                    },
                  }}
                />
              </div>
            ) : (
              <NotData />
            )}
          </>
        )}
      </div>
    </div>
  );
};

export default MessageCenter;
